﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;

namespace Person
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "JsonService" in code, svc and config file together.
    public class JsonService : IJsonService
    {

        public Person[] getPeople()
        {
            Collection.people.Clear();
            MySqlConnectionStringBuilder bag = new MySqlConnectionStringBuilder();
            bag.Server = "localhost";//örn: csharptr.com
            bag.UserID = "visual";
            bag.Password = "root";
            bag.Database = "urun";
            bag.Port = 3306;

            MySqlConnection baglanti = new MySqlConnection(bag.ToString());
            baglanti.Open();

            string sorgu = "Select * from grocerry_list";//Örnek sorgu
            MySqlDataAdapter adaptor = new MySqlDataAdapter(sorgu, baglanti);
            DataSet dataset = new DataSet();
            adaptor.Fill(dataset);
            baglanti.Close();
            foreach (DataRow dRow in dataset.Tables[0].Rows)
            {
                Collection.people.Add(new Person { id = Convert.ToInt32(dRow["id"]), name = dRow["title"].ToString() });
            }  
            return Collection.people.ToArray();
        }

        public Person[] savePeople(string name)
        {
            Collection.people.Add(new Person { id = Collection.people.Count+1, name = name });
            MySqlConnectionStringBuilder bag = new MySqlConnectionStringBuilder();
            bag.Server = "localhost";
            bag.UserID = "visual";
            bag.Password = "root";
            bag.Database = "urun";
            MySqlConnection baglanti = new MySqlConnection(bag.ToString());
            baglanti.Open();
            string sorgu = "insert into grocerry_list(title) values ('"+ name +"')";
            MySqlCommand cmd = new MySqlCommand(sorgu, baglanti);
            cmd.ExecuteNonQuery();
            baglanti.Close();
            return getPeople();
        }

        public class Collection
        {
            public static List<Person> people = new List<Person>
            {
                //new Person{id=1,name="ilker"},
                //new Person{id=2,name="yigit"}
            };
        }
    }
}
